package cn.iocoder.yudao.module.reading.service.banner;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.reading.controller.admin.banner.vo.BannerPageReqVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.banner.BannerDO;
import cn.iocoder.yudao.module.reading.dal.mysql.banner.BannerMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;

/**
 * 横幅管理 Service 实现类
 *
 * @author 李晨
 */
@Service
@Validated
@Slf4j
public class BannerServiceImpl implements BannerService {

    @Resource
    private BannerMapper bannerMapper;

    @Override
    public List<BannerDO> getActiveBanners() {
        return bannerMapper.selectActiveBanners();
    }

    @Override
    public List<BannerDO> getActiveBanners(Integer limit) {
        return bannerMapper.selectActiveBanners(limit);
    }

    @Override
    public BannerDO getBanner(Long id) {
        return bannerMapper.selectById(id);
    }

    @Override
    public BannerDO getBannerByTitle(String title) {
        return bannerMapper.selectByTitle(title);
    }

    @Override
    public void recordBannerClick(Long id) {
        // 验证横幅是否存在
        BannerDO banner = getBanner(id);
        if (banner == null) {
            log.warn("横幅不存在，ID: {}", id);
            return;
        }
        
        // 更新点击次数
        bannerMapper.incrementClickCount(id);
        log.info("横幅点击记录成功，ID: {}, 标题: {}", id, banner.getTitle());
    }

    @Override
    public Long createBanner(String title, String description, String imageUrl, String linkUrl,
                            String linkType, Integer sortOrder, Boolean status,
                            LocalDateTime startTime, LocalDateTime endTime) {
        // 数据验证
        validateBannerData(title, imageUrl, linkType, startTime, endTime);
        
        // 检查标题是否重复
        BannerDO existingBanner = getBannerByTitle(title);
        if (existingBanner != null) {
            throw exception(BAD_REQUEST, "横幅标题已存在");
        }

        // 创建横幅
        BannerDO banner = BannerDO.builder()
                .title(title)
                .description(description)
                .imageUrl(imageUrl)
                .linkUrl(linkUrl)
                .linkType(linkType != null ? linkType : "internal")
                .sortOrder(sortOrder != null ? sortOrder : 0)
                .status(status != null ? status : true)
                .startTime(startTime)
                .endTime(endTime)
                .clickCount(0)
                .build();

        bannerMapper.insert(banner);
        log.info("横幅创建成功，ID: {}, 标题: {}", banner.getId(), title);
        return banner.getId();
    }

    @Override
    public void updateBanner(Long id, String title, String description, String imageUrl, String linkUrl,
                            String linkType, Integer sortOrder, Boolean status,
                            LocalDateTime startTime, LocalDateTime endTime) {
        // 验证横幅是否存在
        BannerDO existingBanner = getBanner(id);
        if (existingBanner == null) {
            throw exception(BAD_REQUEST, "横幅不存在");
        }

        // 数据验证
        validateBannerData(title, imageUrl, linkType, startTime, endTime);
        
        // 检查标题是否重复（排除自己）
        BannerDO bannerWithSameTitle = getBannerByTitle(title);
        if (bannerWithSameTitle != null && !bannerWithSameTitle.getId().equals(id)) {
            throw exception(BAD_REQUEST, "横幅标题已存在");
        }

        // 更新横幅
        BannerDO updateBanner = BannerDO.builder()
                .id(id)
                .title(title)
                .description(description)
                .imageUrl(imageUrl)
                .linkUrl(linkUrl)
                .linkType(linkType != null ? linkType : "internal")
                .sortOrder(sortOrder != null ? sortOrder : 0)
                .status(status != null ? status : true)
                .startTime(startTime)
                .endTime(endTime)
                .build();

        bannerMapper.updateById(updateBanner);
        log.info("横幅更新成功，ID: {}, 标题: {}", id, title);
    }

    @Override
    public void deleteBanner(Long id) {
        // 验证横幅是否存在
        BannerDO banner = getBanner(id);
        if (banner == null) {
            throw exception(BAD_REQUEST, "横幅不存在");
        }

        bannerMapper.deleteById(id);
        log.info("横幅删除成功，ID: {}, 标题: {}", id, banner.getTitle());
    }

    @Override
    public PageResult<BannerDO> getBannerPage(BannerPageReqVO pageReqVO) {
        return bannerMapper.selectPage(pageReqVO);
    }

    @Override
    public void updateBannerStatusBatch(List<Long> ids, Boolean status) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        
        bannerMapper.updateStatusBatch(ids, status);
        log.info("批量更新横幅状态成功，数量: {}, 状态: {}", ids.size(), status);
    }

    @Override
    public void deleteBannerBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        
        bannerMapper.deleteBatchIds(ids);
        log.info("批量删除横幅成功，数量: {}", ids.size());
    }

    /**
     * 验证横幅数据
     */
    private void validateBannerData(String title, String imageUrl, String linkType,
                                   LocalDateTime startTime, LocalDateTime endTime) {
        if (title == null || title.trim().isEmpty()) {
            throw exception(BAD_REQUEST, "横幅标题不能为空");
        }
        
        if (title.length() > 100) {
            throw exception(BAD_REQUEST, "横幅标题长度不能超过100个字符");
        }
        
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            throw exception(BAD_REQUEST, "横幅图片不能为空");
        }
        
        if (imageUrl.length() > 500) {
            throw exception(BAD_REQUEST, "横幅图片URL长度不能超过500个字符");
        }
        
        if (linkType != null && !linkType.equals("internal") && !linkType.equals("external")) {
            throw exception(BAD_REQUEST, "链接类型只能是internal或external");
        }
        
        if (startTime != null && endTime != null && startTime.isAfter(endTime)) {
            throw exception(BAD_REQUEST, "开始时间不能晚于结束时间");
        }
    }

}
